package cn.cms.util;

import cn.cms.webcommon.ResBo;
import com.alibaba.fastjson.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

public class ResponseUtil {

    private static Logger logger = LoggerFactory.getLogger(ResponseUtil.class);

    /**
     * Ajax响应输出开始信息
     */
    private static final String AJAX_PACKET_STR = "var response = new AJAXPacket();";

    /**
     * Ajax响应输出响应信息
     */
    private static final String AJAX_PACKET_END = "core.ajax.receivePacket(response);";

    /**
     * 编码格式
     */
    private static final String PAGE_ENCODING = "UTF-8";

    /**
     * 构造函数私有化
     */
    private ResponseUtil() {

    }

    /**
     * 把信息通过输出流输出到界面
     *
     * @param response HttpServletResponse对象-Action中通过HttpServletResponse response =
     *                 ServletActionContext.getResponse()获取
     * @param printObj String-要输出到界面的字符串
     */
    public static void printAjax(HttpServletResponse response, Object printObj) {
        response.setContentType("text/html; charset=" + PAGE_ENCODING);
        response.setHeader("Cache-Control", "no-cache");
        PrintWriter out;
        try {
            out = response.getWriter();
            out.println(JSONObject.toJSONString(printObj));
            out.close();
        } catch (IOException e) {
            logger.error("Error:Cannot create PrintWriter Object !");
        }
    }

    /**
     * 把信息通过输出流输出到界面
     *
     * @param response HttpServletResponse对象-Action中通过HttpServletResponse response =
     *                 ServletActionContext.getResponse()获取
     * @param resBo    要输出到界面的对象
     * @throws java.io.IOException
     */
    public static void printAjaxPack(HttpServletResponse response, ResBo resBo) {
        response.setContentType("text/html; charset=" + PAGE_ENCODING);
        response.setHeader("Cache-Control", "no-cache");
        PrintWriter out;
        try {
            out = response.getWriter();
            out.println(AJAX_PACKET_STR);
            // 得到resBo的json字符串
            String jsonStr = JSONObject.toJSONString(resBo);
            if (logger.isDebugEnabled()) {
                logger.debug("jsonStr = " + jsonStr);
            }
            out.println("response.data=eval(" + jsonStr + ")");
            out.println(AJAX_PACKET_END);
            out.close();
        } catch (IOException e) {
            logger.warn("输出信息错误", e);
        }
    }

}
